package com.hengpeng.itfints.controller.project;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.persist.ProjectInfo;
import com.hengpeng.itfinbase.persist.ProjectInfo.FundType;
import com.hengpeng.itfinbase.persist.ProjectInfo.InvestType;
import com.hengpeng.itfinbase.persist.ProjectInfo.ProjectType;
import com.hengpeng.itfinbase.persist.ProjectInfoContacts;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfints.constants.SystemConfigUtil;
import com.hengpeng.itfints.constants.TSConstants;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.service.ServiceFactory;
import com.hengpeng.itfints.tools.PageUtil;
import com.hengpeng.itfints.vo.MemberSession;

/**
 * <pre>
 * 新闻公告
 * </pre>
 * @author weiyuan
 * @version 1.0, 2015年8月24日
 */
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController
{
	public final static Log logger = LogFactory.getLog(ProjectController.class);

	@Autowired
	private ServiceFactory serviceFactory;

	/**
	 * <pre>
	 * 项目列表
	 * </pre>
	 * @param map
	 * @param request
	 * @param borrowName
	 * @param borrowUserName
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(ModelMap map, HttpServletRequest request, String curPage, String bussinessType,
			String location, String financeType,String gm ,ProjectType projectType,
			InvestType investType,FundType fundType,String tzje)
	{
		
		int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);
		ServiceResult<List<ProjectInfo>> serviceResult = serviceFactory.getProjectService()
				.queryList(int_curPage, 10, bussinessType,
				 location,  financeType, gm,projectType,null,
				 investType, fundType, tzje);
		PageUtil pUtil = new PageUtil(10, serviceResult.getReturnListSize(), int_curPage);
		map.put("dataList", serviceResult.getReturnValue());
		map.put("PageUtil", pUtil);
		
		map.put("bussinessType", bussinessType);
		map.put("location", location);
		map.put("financeType", financeType);
		map.put("gm", gm);
		
		map.put("investType", investType);
		map.put("fundType", fundType);
		map.put("tzje", tzje);
		if (projectType == ProjectType.PROJECTFINACE) {
			return "/page/project/projectlist.jsp";
		} else if (projectType == ProjectType.PROPERTYTRADE) {
			return "/page/project/fundlist.jsp";
		}
		return "";
	}
	@RequestMapping(value = "/myprojectlist")
	public String myprojectlist(ModelMap map, HttpServletRequest request, String curPage)
	{
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);
		ServiceResult<List<ProjectInfo>> serviceResult = serviceFactory.getProjectService().queryList(int_curPage, 10, null,
				null,  null, null,null,member.getUser().getId(),
				null,null,null);
		PageUtil pUtil = new PageUtil(10, serviceResult.getReturnListSize(), int_curPage);
		map.put("dataList", serviceResult.getReturnValue());
		map.put("PageUtil", pUtil);
		return "/page/account/project/myprojectlist.jsp";
	}
	@RequestMapping(value = "/myprojectdetail")
	public String myprojectdetail(ModelMap map, HttpServletRequest request, String id)
	{
		ProjectInfo projectInfo = serviceFactory.getPersistService().get(ProjectInfo.class, Long.parseLong(id));
		map.put("projectInfo", projectInfo);
		if (projectInfo.getProjectType() == ProjectInfo.ProjectType.PROJECTFINACE) {
			return "/page/account/project/myprojectdetail.jsp";
		} else if (projectInfo.getProjectType() == ProjectInfo.ProjectType.PROPERTYTRADE) {
			return "/page/account/project/mytradedetail.jsp";
		}
		return "";
	}
	/**
	 * 查看详细
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/detail")
	public String detail(Long id, ModelMap map)
	{
		ProjectInfo obj = serviceFactory.getPersistService().get(ProjectInfo.class, id);
		map.put("project", obj);
		return "/page/project/detail.jsp";
	}
	/**
	 * 转向预约
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/toOrder", method = RequestMethod.GET)
	public String toOrder(HttpServletRequest request,  ModelMap map, String projectId) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		ProjectInfo project = serviceFactory.getPersistService().get(ProjectInfo.class, Long.parseLong(projectId));
		if (member == null)
		{
			return "/page/borrowInfo/needLogin.jsp";//转到登录页面
		}
		map.put("project", project);
		return "/page/project/order.jsp";
	}
	/**
	 * 添加预约信息
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/order", method = RequestMethod.POST)
	public String order(HttpServletRequest request, ModelMap map, ProjectInfoContacts projectInfoContacts) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		ProjectInfo project = serviceFactory.getPersistService().get(ProjectInfo.class, projectInfoContacts.getProjectId());
		
		projectInfoContacts.setStartUserId(member.getUser().getId());//
		projectInfoContacts.setStartUserName(member.getUser().getUserName());//
		
		projectInfoContacts.setReceiveUserId(project.getPublishUserId());
		projectInfoContacts.setCreateTime(new Date());
		projectInfoContacts.setUpdateTime(new Date());
		projectInfoContacts = serviceFactory.getPersistService().save(projectInfoContacts);
		if (projectInfoContacts.getId() != null) {
			map.put("message", "您的预约已添加成功");
		} else {
			map.put("message", "您的预约添加失败");
		}
		map.put("backurl",request.getContextPath() + "/project/list.htm?projectType=PROJECTFINACE");
		return "/page/common/result_back.jsp";
		
//		return "/project/list.htm";
	}
	/**
	 * 转向投递项目
	 * @param request
	 * @param map
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value = "/totd", method = RequestMethod.GET)
	public String totd(HttpServletRequest request,  ModelMap map, String projectId) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		ProjectInfo project = serviceFactory.getPersistService().get(ProjectInfo.class, Long.parseLong(projectId));
		if (member == null)
		{
			return "/page/borrowInfo/needLogin.jsp";//转到登录页面
		}
		map.put("project", project);
		return "/page/project/td.jsp";
	}
	/**
	 * 添加预约信息
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/td", method = RequestMethod.POST)
	public String td(HttpServletRequest request, ModelMap map, ProjectInfoContacts projectInfoContacts) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		
		ProjectInfo project = serviceFactory.getPersistService().get(ProjectInfo.class, projectInfoContacts.getProjectId());
		
		projectInfoContacts.setStartUserId(member.getUser().getId());//
		projectInfoContacts.setStartUserName(member.getUser().getUserName());//
		
		projectInfoContacts.setReceiveUserId(project.getPublishUserId());
		
		projectInfoContacts.setCreateTime(new Date());
		projectInfoContacts.setUpdateTime(new Date());
		projectInfoContacts = serviceFactory.getPersistService().save(projectInfoContacts);
//		if (projectInfoContacts.getId() != null) {
//			map.put("info", "添加成功");
//		} else {
//			map.put("info", "添加失败");
//		}
//		return "/project/list.htm?projectType=PROPERTYTRADE";
//		
		if (projectInfoContacts.getId() != null) {
			map.put("message", "您的投递已添加成功");
		} else {
			map.put("message", "您的投递添加失败");
		}
		map.put("backurl",request.getContextPath() + "/project/list.htm?projectType=PROPERTYTRADE");
		return "/page/common/result_back.jsp";
	}
	/**
	 * 上传商业计划书
	 * @param request
	 * @param response
	 * @param map
	 * @param plan
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/importplan", method = RequestMethod.POST)
	public String importplan (HttpServletRequest request,HttpServletResponse response, ModelMap map,
			@RequestParam MultipartFile plan) throws Exception {
		
		response.setContentType("text/html;charset=GBK");
	    request.setCharacterEncoding("GBK");
	    if (plan.getSize() > 2 * 1024 * 1024) {
			map.put("info", "导入文件最大不能超过2M");
		} else {
			String filePath = request.getRealPath("/upload");// 取系统当前路径
			String newfileName = System.currentTimeMillis()+ plan.getOriginalFilename().substring(plan.getOriginalFilename().lastIndexOf('.'));
			OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);
			InputStream in = plan.getInputStream();
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			in.close();
	        map.put("info", "success");
	        map.put("filename", newfileName);
	        map.put("filepath", SystemConfigUtil.getConfigValue("domainName") + "upload/" + newfileName);
		}
        return "/page/project/importfile.jsp";
	}
	/**
	 * 转向发布
	 * @param request
	 * @param map
	 * @param userInfoType
	 * @return
	 */
	@RequestMapping(value = "/p_topublish", method = RequestMethod.GET)
	public String p_topublish(HttpServletRequest request, ModelMap map, UserInfoType userInfoType) {
		if (userInfoType == UserInfoType.ENTERPRISE) {//转向企业发布
			return "/page/account/project/step_one.jsp";
		} else if (userInfoType == UserInfoType.FINANCEDEPT) {//专项金融机构发布
			return "/page/account/project/filltrade.jsp";
		}
		return "";
	}
	/**
	 * 保存发布项目信息
	 * @param request
	 * @param map
	 * @param projectInfo
	 * @return
	 */
	@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
	public String saveProject(HttpServletRequest request, ModelMap map, ProjectInfo projectInfo) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		projectInfo.setUpdateTime(new Date());
		projectInfo.setCreateTime(new Date());
		projectInfo.setPublishUserId(member.getUser().getId());
		serviceFactory.getPersistService().save(projectInfo);
		return "/page/account/project/success.jsp";
	}
	/**
	 * 我收到的约谈信息
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/myreceiveList")
	public String myreceiveList(HttpServletRequest request, ModelMap map, String curPage) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);
		ServiceResult<List<ProjectInfoContacts>> serviceResult = serviceFactory.getProjectService().myreceiveList
				(int_curPage, 10, member.getUser().getId());;
		PageUtil pUtil = new PageUtil(10, serviceResult.getReturnListSize(), int_curPage);
		map.put("dataList", serviceResult.getReturnValue());
		map.put("PageUtil", pUtil);
		return "/page/account/project/myreceiveList.jsp";
	}
	/**
	 * 我发起的投递
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/myorderList")
	public String myorderList(HttpServletRequest request, ModelMap map, String curPage) {
		MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);
		ServiceResult<List<ProjectInfoContacts>> serviceResult = serviceFactory.getProjectService().myorderList
				(int_curPage, 10, member.getUser().getId());;
		PageUtil pUtil = new PageUtil(10, serviceResult.getReturnListSize(), int_curPage);
		map.put("dataList", serviceResult.getReturnValue());
		map.put("PageUtil", pUtil);
		return "/page/account/project/myorderList.jsp";
	}
}
